package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.dtos.AdUserDto;
import com.heima.admin.pojos.AdUser;
import com.heima.admin.service.AdUserService;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 郭文杰
 * @description 针对表【ad_user(管理员用户信息表)】的数据库操作Service实现
 * @createDate 2024-04-05 15:24:12
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser>
        implements AdUserService {

    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        //1.检查参数
        if (adUserDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //2.查询用户是否存在
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDto.getName()));
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_OR_PHONE_EMPTY);
        }

        //3.比对密码是否正确
        String salt = adUser.getSalt();
        String password = DigestUtils.md5DigestAsHex((adUserDto.getPassword() + salt).getBytes());
        if (password.equals(adUser.getPassword())) {
            //设置token
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
            adUser.setSalt("");
            adUser.setPassword("");
            map.put("user", adUser);
            return ResponseResult.okResult(map);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }
}




